#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include "FileNotFoundException"
#include "struct_ul.h"
using namespace std;

//根据文件内容读入vector
int createBooks(const char *fileName, vector<script_item*> &script_items) {
    int booknums;
	int id;
    string class_id, name, publisher, writer;
    long long exp;
    int res_num;
    string edition;
    time_t publisher_time;
    int num, has_brorrow;
    string line;

    cout << "从文件" << fileName << "中读入数据，生成书本清单" << endl;
    ifstream fileStream(fileName);

    if (fileStream.rdstate() & ios::failbit) {
        ostringstream message;
        message << "不能打开文件" << fileName << "，请确认文件路径是否正确" ;
        throw FileNotFoundException(message.str());
    }

    while (getline(fileStream, line)) {
        istringstream strStream(line);
        strStream >> id;
        strStream >> class_id >> name >> publisher >> writer >> exp >> res_num >> edition >> publisher_time >> num >> has_brorrow;
        script_item* ptr = new script_item(id, class_id, name, publisher, writer, exp, res_num, edition, publisher_time, num, has_brorrow);
        script_items[bookNums++] = ptr;
    }

    for (int i = 0; i < bookNums; i ++) script_items[i]->showInfo();
    return bookNums;
}

//将vector里的数据写入二进制文件
void outputBinaryFiles(vector<script_item*> &books, int bookNums) {
    cout << "将数组中的内容写入二进制文件" << endl;
    ofstream bookFile("script_item.dat", ios_base::out | ios_base::binary);
    for (int i = 0; i < bookNums; i ++ ) {
        bookFile.write(reinterpret_cast<char*>(books[i]), sizeof(*books[i]));
    }
    bookFile.close();
    cout << "二进制文件写入完成。" << endl;
}

//从二进制文件中读取数据，并存到vector里
void readBinaryFiles(vector<script_item*> &books, int bookNums) {
    cout << "从二进制文件中读取数据。" << endl;
    ifstream bookFile("Books.dat", ios_base::in | ios_base::binary);
    int i = 0;
    while (bookFile.read(reinterpret_cast<char*>(books[i]), sizeof(*books[i]))) {
        books[i++]->showInfo();
    }

    bookFile.close();
    cout << "文件读取操作完成。" << endl;
}

/*
int main() {
    const int N = 100010;
    vector<script_item*> books(N, nullptr);

    int bookNums = 0;
    try {
        bookNums = createBooks("info_script_items.txt", books);
    } catch (FileNotFoundException &e){
        cout << e.what() << endl;
    }

    outputBinaryFiles(books, bookNums);
    readBinaryFiles(books, bookNums);

    return 0;
}
*/